
package nccloud.rongq.bill.rongqvo.action;

import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import nc.arap.pub.cons.DefDocCons;
import nc.arap.pub.cons.SQLCons;
import nc.bs.logging.Logger;
import nc.itf.uap.IUAPQueryBS;
import nc.jdbc.framework.processor.ColumnProcessor;
import nc.jdbc.framework.processor.MapListProcessor;
import nc.vo.pub.BusinessException;
import nc.vo.pub.CircularlyAccessibleValueObject;
import nc.vo.rongq.rongq.AggRongQVO;
import nc.vo.rongq.rongq.RongQBVO;
import nccloud.framework.core.exception.ExceptionUtils;
import nccloud.framework.service.ServiceLocator;
import nccloud.framework.web.action.itf.ICommonAction;
import nccloud.framework.web.container.IRequest;
import nccloud.framework.web.ui.pattern.billcard.BillCardOperator;
import nccloud.pubitf.riart.pflow.CloudPFlowContext;
import nccloud.pubitf.riart.pflow.ICloudScriptPFlowService;
import nccloud.rongq.bill.rongqvo.bill.util.CommonUtil;
import nccloud.vo.rongq.bill.RongQVOConst;

/**
 * 主子表保存
 * @version  @since v3.5.6-1903
 */
public class RongQVOSaveAction implements ICommonAction {

  @Override
  public Object doAction(IRequest paramIRequest) {
    try {
      BillCardOperator billCardOperator = new BillCardOperator();
      // 1、获取AGGVO （request转换主子VO）
AggRongQVO vo = billCardOperator.toBill(paramIRequest);
      this.doBefore(vo);
      // 2、调用单据的保存动作脚本（savebase），得到保存后结果
AggRongQVO rtnObj = this.callActionScript(vo);
      // 3、处理返回结果（包含功能：根据模板转换前端BillCard，参照翻译，显示公式处理）
      Object billcard = billCardOperator.toCard(rtnObj);
      // 4、返回结果到前端
      return billcard;
    }
    catch (BusinessException ex) {
      // 处理异常信息
      Logger.error(ex);
      ExceptionUtils.wrapException(ex);
    }
    return null;
  }

  /**
   * 动作编码
   *
   * @return
   */
  protected String getActionCode() {
    return RongQVOConst.CONST_ACTION_SAVEBASE;
  }

  /**
   * 调用动作脚本
   *
   * @param actionCode
   * @param aggVOs
   * @return
   * @throws BusinessException
   */
  private AggRongQVO callActionScript(AggRongQVO... aggVOs)
      throws BusinessException {

    String actionCode = this.getActionCode();
    String billType = RongQVOConst.CONST_BILLTYPE_COST;

    CloudPFlowContext context = new CloudPFlowContext();
    context.setActionName(actionCode);
    context.setBillType(billType);
    context.setBillVos(aggVOs);
    Logger.debug("开始调用动作脚本 ActionName[" + actionCode + "] BillType[" + billType
        + "]...");

    ICloudScriptPFlowService service =
        CommonUtil.getCloudScriptPFlowService();

    Object[] result = service.exeScriptPFlow(context);

    Logger.debug("调用动作脚本 ActionName[" + actionCode + "] BillType[" + billType
        + "]结束");

    String wheresql =
        "pk_rongq_h" + "='"
            + ((AggRongQVO) result[0]).getPrimaryKey() + "'";
    Collection<AggRongQVO> bills =
        CommonUtil.getMDPersistenceQueryService().queryBillOfVOByCond(
            AggRongQVO.class, wheresql, true, false);
    return bills.toArray(new AggRongQVO[0])[0];
  }

  /**
   * 判断新增或修改
   *
   * @param vo
   */
  private void doBefore(AggRongQVO vo) {
    String parentPk = vo.getPrimaryKey();
    IUAPQueryBS iuap = ServiceLocator.find(IUAPQueryBS.class);
    RongQBVO[] bvos =(RongQBVO[]) vo.getChildrenVO();
    if(bvos.length==0) {
    	ExceptionUtils.wrapBusinessException("表体数据为空，不允许保存");
    }
    for(int i = 0;i<bvos.length;i++) {
    	//校验科目辅助核算
    	if(bvos[i].getAcc() != null) {
    		try {
    			List<Map<String, Object>> list = (List<Map<String, Object>>) iuap.executeQuery(SQLCons.getChecktypeByAccID(bvos[i].getAcc()), new MapListProcessor());
    			
    			String temp = null;
    			if(list != null && list.size() > 0) {
    				for(Map<String, Object> map : list) {
    					temp = (String) map.get("checktypecode");
    					if(temp.equals(DefDocCons.CHECKTYPE_CPH)) {
    						if(StringUtils.isEmpty(bvos[i].getDef5())) {
    							ExceptionUtils.wrapBusinessException("表体的第" + (i + 1) + "行辅助车牌号不能为空");
    							return;
    						}
    					}else if(temp.equals(DefDocCons.CHECKTYPE_KS)) {
    						if(StringUtils.isEmpty(bvos[i].getDef7())) {
    							ExceptionUtils.wrapBusinessException("表体的第" + (i + 1) + "行辅助客商不能为空");
    							return;
    						}
    					}else if(temp.equals(DefDocCons.CHECKTYPE_RY)) {
    						if(StringUtils.isEmpty(bvos[i].getDef10())) {
    							ExceptionUtils.wrapBusinessException("表体的第" + (i + 1) + "行辅助人员档案不能为空");
    							return;
    						}
    					}else if(temp.equals(DefDocCons.CHECKTYPE_XMMC)) {
    						if(StringUtils.isEmpty(bvos[i].getDef11())) {
    							ExceptionUtils.wrapBusinessException("表体的第" + (i + 1) + "行辅助项目名称不能为空");
    							return;
    						}
    					}else if(temp.equals(DefDocCons.CHECKTYPE_HTBH)) {
    						if(StringUtils.isEmpty(bvos[i].getDef12())) {
    							ExceptionUtils.wrapBusinessException("表体的第" + (i + 1) + "行辅助合同编号不能为空");
    							return;
    						}
    					}
    				}
    			}
    			
    		} catch (BusinessException e) {
    			e.printStackTrace();
    			ExceptionUtils.wrapBusinessException(e.getMessage());
    		}
    	}
    	
    	//校验报销类型
    	if(bvos[i].getDef1() != null) {
    		String billno = bvos[i].getBillno();
			String def7 = bvos[i].getDef7();
			String def9 = bvos[i].getDef9();
    		String sql = "select code from bd_defdoc where pk_defdoc = '"+bvos[i].getDef1()+"'";
    		try {
				String code = (String) iuap.executeQuery(sql, new ColumnProcessor());
				if("15".equals(code)) {//招待费
					String def6 = bvos[i].getDef6();
					if(StringUtils.isEmpty(def6)) {
						ExceptionUtils.wrapBusinessException("表体的第" + (i + 1) + "行客户类型不能为空");
					}
					//校验客户类型
					String type = "select name from bd_defdoc where pk_defdoc = '"+def6+"'";
					String tname = (String) iuap.executeQuery(type, new ColumnProcessor());
					if("合作客户".equals(tname)) {
						if(StringUtils.isEmpty(def7)) {
							ExceptionUtils.wrapBusinessException("表体的第" + (i + 1) + "行客商不能为空");
						}
					}else if("意向客户".equals(tname)) {
						if(StringUtils.isEmpty(def9)) {
							ExceptionUtils.wrapBusinessException("表体的第" + (i + 1) + "行意向客户不能为空");
						}
					}
				}else if("02".equals(code) || "38".equals(code) || "33".equals(code)) {
					//其他成本：02  //货损支出：38  //外包劳务费：33
					if(StringUtils.isEmpty(def7)) {
						ExceptionUtils.wrapBusinessException("表体的第" + (i + 1) + "行客商不能为空");
					}
					if("38".equals(code)) {
						if(StringUtils.isEmpty(billno) || StringUtils.isEmpty(def7)) {
							ExceptionUtils.wrapBusinessException("表体的第" + (i + 1) + "行客商、cp单号不能为空");
						}
					}
				}else if("29".equals(code) || "30".equals(code) || "31".equals(code) || "32".equals(code) || "21".equals(code) || "08".equals(code) || "40".equals(code)) {
					//加油费：29//路桥费：30//修理费（含轮胎）：31//其他车辆成本：32//车辆事故损失：40//公务车报销类型档案编码21
//					叉车费用报销类型档案编码08
					if(StringUtils.isEmpty(bvos[i].getDef5())) {
						ExceptionUtils.wrapBusinessException("表体的第" + (i + 1) + "行车牌号不能为空");
					}
				}
				
				if(StringUtils.isNotEmpty(def7)) {
					//客商必填，业务类型必填
					if(StringUtils.isEmpty(bvos[i].getDef8())) {
						ExceptionUtils.wrapBusinessException("表体的第" + (i + 1) + "行客商必填，业务类型必填");
					}
				}
				
				
			} catch (BusinessException e) {
				e.printStackTrace();
				ExceptionUtils.wrapBusinessException(e.getMessage());
			}
    	}
	}

    // 根据是否有主键信息判断是新增保存还是修改保存
    if ((parentPk != null) && !"".equals(parentPk)) {
      // 设置单据默认值
      CircularlyAccessibleValueObject[] allchildren = vo.getAllChildrenVO();
      if (allchildren != null) {
        for (CircularlyAccessibleValueObject obj : allchildren) {
          obj.setAttributeValue("pk_rongq_h", parentPk);
        }
      }
    }
  }
}
